<template>
	<!-- 自定义头部 -->
	<u-navbar title="模具维修" bgColor="#FBFBFF" :autoBack="true" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
		<template #right>
			<view class="u-nav-slot" v-if="taskInfo.repairStatus == '2' || taskInfo.repairStatus == '1' || taskInfo.repairStatus == '0'" @click="showEdit = true">
				<image src="/static/icons/more_edit.svg" style="width: 60rpx; height: 60rpx; margin-top: 10rpx"></image>
			</view>
		</template>
	</u-navbar>
	<view class="baseForm">
		<u-loading-page :loading="loading"></u-loading-page>
		<view v-if="!loading" class="overhidden">
			<!-- 工单头部编号&状态样式 -->
			<view v-if="props.id" class="" style="width: 100%; background-color: rgba(22, 37, 78, 0.85); height: 110px">
				<view class="" style="padding: 22px 15px; display: flex; justify-content: space-between">
					<view class="" style="display: flex; flex-direction: column">
						<text style="font-size: 18px; color: #fff; font-weight: bold">{{ useDictionaryStore().filterDictName('EamRepairStatus', taskInfo.repairStatus) }}</text>
						<text style="font-size: 15px; color: #fff; margin-top: 9px">报修编号：{{ taskInfo.repairCode }}</text>
					</view>
					<image v-show="taskInfo.repairTeamText" src="@/static/image/order.png" style="width: 50px; height: 50px" />
				</view>
			</view>

			<!-- 查看页面样式 -->
			<view v-if="props.isRead == 1" class="mt-10-">
				<!-- 设备详情 -->
				<DeviceInfoTemplate :taskInfo="toRaw(taskInfo)"></DeviceInfoTemplate>
				<!-- 故障信息 -->
				<RepairOrderInfo :taskInfo="toRaw(taskInfo)"></RepairOrderInfo>
				<!-- 维修信息 -->
				<RepairHandleInfo :taskInfo="toRaw(taskInfo)"></RepairHandleInfo>
			</view>

			<!-- 编辑页面样式 -->
			<view v-if="props.isRead == 0" class="mt-10-">
				<!-- bgColor="#0F40F5" -->
				<view class="repaire_tag_div">
					<view class="repaire_tag">
						<view class="tag_item" :class="tagCurrent === 0?'active_tag':''" @click="selectTagHandle(0)">故障信息</view>
						<view class="tag_item" :class="tagCurrent === 1?'active_tag':''" @click="selectTagHandle(1)">维修信息</view>
					</view>
				</view>
				<!-- <u-subsection :list="tabList" :current="tagCurrent" mode="subsection" activeColor="#0379FF" @change="sectionChange" class="repaireTag"></u-subsection> -->

				<u--form labelPosition="top" :model="taskInfo" :rules="rules" labelWidth="300" ref="uForm" class="form" errorType="toast">
					<!-- 设备详情 -->
					<DeviceInfoTemplate v-show="tagCurrent === 0" :taskInfo="taskInfo"></DeviceInfoTemplate>
					<!-- 故障信息 -->
					<RepairOrderInfo v-show="tagCurrent === 0" :taskInfo="taskInfo" @fileChange="getImageFiles"></RepairOrderInfo>
					<!-- 维修编辑信息 -->
					<view v-show="tagCurrent === 1" class="plan card record-content">
						<view class="" v-if="Number(taskInfo.repairStatus) >= 4">
							<view class="title flex justify-between">
								<text>基础信息</text>
							</view>
							<view class="">
								<view class="record-item" v-show="taskInfo?.repairStartTime" style="margin-top: 0px">
									<text>维修开始时间</text>
									<text>{{ taskInfo?.repairStartTime || '' }}</text>
								</view>
								<view class="record-item" v-show="taskInfo?.repairEndTime" style="margin-top: 0px">
									<text>维修结束时间</text>
									<text>{{ taskInfo?.repairEndTime || '' }}</text>
								</view>
								<!-- <view class="record-item" v-show="taskInfo?.faultMode" style="margin-top: 0px">
									<text>故障模式</text>
									<text>{{ taskInfo?.faultMode || '' }}</text>
								</view>
								<view class="record-item" v-show="taskInfo?.faultStatus" style="margin-top: 0px">
									<text>故障状态</text>
									<text>{{ useDictionaryStore().filterDictName('EamFaultStatus', taskInfo.faultStatus) }}</text>
								</view>
								<view class="record-item" v-show="taskInfo?.repairLevel" style="margin-top: 0px">
									<text>故障等级</text>
									<text>{{ useDictionaryStore().filterDictName('EamFaultLevel', taskInfo.repairLevel) }}</text>
								</view> -->
							</view>
						</view>
						<view class="" v-else>
							<view class="title flex justify-between">
								<text>基础信息（必填）</text>
							</view>
							<view class="question">
								<view>
									<u-form-item label="维修开始时间" prop="repairStartTime">
										<view class="record-item" v-show="taskInfo?.repairStartTime" style="margin-top: 0px">
										<!-- <view @click="openTimeSelect" class="flex input-box"> -->
											<u--input v-model="taskInfo.repairStartTime" border="none" disabled disabledColor="#ffffff" placeholder="请选择维修开始时间"></u--input>
											<!-- <image
												@click.stop="clearInfo(['repairStartTime', 'repairStartTimeCode'])"
												v-show="taskInfo.repairStartTime"
												src="@/static/image/delete.png"
											/>
											<image v-show="!taskInfo.repairStartTime" src="@/static/image/calendar.png" style="width: 16px; height: 16px; margin-top: 2px" /> -->

										</view>
									</u-form-item>
									<u-form-item label="维修结束时间" prop="repairEndTime">
										<view @click="openTimeSelectEnd" class="flex input-box">
											<u--input v-model="taskInfo.repairEndTime" border="none" disabled disabledColor="#ffffff" placeholder="请选择维修结束时间"></u--input>
											<image
												@click.stop="clearInfo(['repairEndTime', 'repairEndTimeCode'])"
												v-show="taskInfo.repairEndTime"
												src="@/static/image/delete.png"
											/>
											<image v-show="!taskInfo.repairEndTime" src="@/static/image/calendar.png" style="width: 16px; height: 16px; margin-top: 2px" />
										</view>
									</u-form-item>
									<!-- <u-form-item label="故障模式" prop="faultModeId">
										<view @click="modeHideKeyboard" class="flex input-box">
											<u--input v-model="taskInfo.faultMode" border="none" placeholder="请选择故障模式" readonly class="input-self"></u--input>
											<image @click.stop="clearInfo(['faultMode', 'faultModeId'])" v-show="taskInfo.faultMode" src="@/static/image/delete.png" />
										</view>
									</u-form-item>
									<u-form-item label="故障状态" prop="faultStatus" required>
										<u-radio-group v-model="taskInfo.faultStatus">
											<u-radio
												:customStyle="{ marginRight: '30px', fontSize: '14px' }"
												shape="square"
												v-for="(item, index) in useDictionaryStore().filterDictList('EamFaultStatus')"
												:key="index"
												:label="item.label"
												:name="item.value"
											></u-radio>
										</u-radio-group>
									</u-form-item>
									<u-form-item label="故障等级" prop="repairLevel" required>
										<u-radio-group v-model="taskInfo.repairLevel">
											<u-radio
												:customStyle="{ marginRight: '30px' }"
												shape="square"
												v-for="(item, index) in useDictionaryStore().filterDictList('EamFaultLevel')"
												:key="index"
												:label="item.label"
												:name="item.value"
											></u-radio>
										</u-radio-group>
									</u-form-item> -->
									<!-- 有用 不能删除 -->
									<!-- <u-form-item label="故障部位">
											<view @click="showPositionPicker" class="flex input-box">
												<u--input v-model="taskInfo.faultPosition" border="none" placeholder="请选择故障部位" readonly class="input-self"></u--input>
												<image @click.stop="clearInfo(['faultPosition', 'faultPositionId'])" v-show="taskInfo.faultPosition" src="@/static/image/delete.png" />
											</view>
										</u-form-item> -->
									<!-- <u-form-item label="维修班组">
											<view @click="hideKeyboard" class="flex input-box">
												<u--input v-model="taskInfo.repairTeamText" border="none" placeholder="请选择维修班组" readonly class="input-self"></u--input>
												<image @click.stop="changeCrew({})" v-show="taskInfo.repairTeamText" src="@/static/image/delete.png" />
											</view>
										</u-form-item>
										<u-form-item label="维修人">
											<view @click="crewhideKeyboard" class="flex input-box">
												<u--input v-model="taskInfo.repairTeamUserText" border="none" placeholder="请选择维修人" readonly class="input-self"></u--input>
												<image @click.stop="changeMember({})" v-show="taskInfo.repairTeamUserText" src="@/static/image/delete.png" />
											</view>
										</u-form-item> -->
								</view>
							</view>
						</view>
					</view>

					<view v-show="tagCurrent === 1" class="detail card">
						<view class="flex flex-col justify-between flex-1 h-full">
							<view class="record-content">
								<view class="flex title justify-between" style="margin: 6px 0 !important" @click="() => (isCollapse = !isCollapse)">
									<text>详细信息</text>
									<u-icon v-show="!isCollapse" name="arrow-up" color="#000a7b"></u-icon>
									<u-icon v-show="isCollapse" name="arrow-down" color="#000a7b"></u-icon>
								</view>
								<view v-show="!isCollapse" style="margin-top: 8px">
									<u-form-item label="维修用时 (分钟)" prop="repairUseTime">
										<view class="flex input-box1">
											<u--input v-model="taskInfo.repairUseTime" border="none" placeholder="请输入维修用时" class="input-self"></u--input>
											<image @click.stop="clearInfo(['repairUseTime'])" v-show="taskInfo.repairUseTime" src="@/static/image/delete.png" />
										</view>
									</u-form-item>
									<u-form-item label="故障部位" prop="faultPositionId">
										<view class="flex input-box1">
											<u--input v-model="taskInfo.faultPosition" border="none" placeholder="请输入故障部位" class="input-self"></u--input>
											<image @click.stop="clearInfo(['faultPositionId', 'faultPosition'])" v-show="taskInfo.faultPosition" src="@/static/image/delete.png" />
										</view>
									</u-form-item>
									<u-form-item label="故障现象" prop="faultPhenomenon">
										<view class="flex input-box1">
											<u--input v-model="taskInfo.faultPhenomenon" border="none" placeholder="请输入故障现象" class="input-self"></u--input>
											<image
												@click.stop="clearInfo(['faultPhenomenon', 'faultPhenomenonId'])"
												v-show="taskInfo.faultPhenomenon"
												src="@/static/image/delete.png"
											/>
										</view>
									</u-form-item>
									<u-form-item label="故障原因" prop="faultReason">
										<view class="flex input-box1">
											<u--input v-model="taskInfo.faultReason" border="none" placeholder="请输入故障原因" class="input-self"></u--input>
											<image @click.stop="clearInfo(['faultReasonId', 'faultReason'])" v-show="taskInfo.faultReason" src="@/static/image/delete.png" />
										</view>
									</u-form-item>
									<!-- <u-form-item label="处理措施">
										<view class="flex input-box1">
											<u--input v-model="taskInfo.faultHandleMeasure" border="none" placeholder="请输入处理措施" class="input-self"></u--input>
											<image @click.stop="clearInfo(['faultHandleMeasureId', 'faultHandleMeasure'])" v-show="taskInfo.faultHandleMeasure" src="@/static/image/delete.png" />
										</view>
									</u-form-item> -->
									<u-form-item label="处理措施" prop="faultHandleMeasure">
										<u--textarea
											v-model="taskInfo.faultHandleMeasure"
											placeholder="请输入处理措施"
											height="40px"
											:customStyle="{ marginTop: '2px' }"
										></u--textarea>
									</u-form-item>
									<u-form-item label="情况说明" prop="repairSituation">
										<u--textarea
											v-model="taskInfo.repairSituation"
											placeholder="请输入情况说明"
											height="40px"
											:customStyle="{ marginTop: '2px' }"
										></u--textarea>
									</u-form-item>
									<u-form-item label="维修图片">
										<upload-image
											:multiple="false"
											:accept="accept"
											@fileChange="getSceneExecuteFiles"
											camera="back"
											:list="taskInfo.executeFiles"
											:capture="capture"
											:key="2"
											style="margin-top: 4px"
											folderName="eam/equ/eamRepairHandle"
										></upload-image>
									</u-form-item>

									<view class="record-item" v-show="taskInfo?.answerTime" style="margin-top: 0px">
										<text>应答时间</text>
										<text>{{ taskInfo?.answerTime || '' }}</text>
									</view>
									<view class="record-item" v-show="taskInfo?.repairTeamName">
										<text>维修班组</text>
										<text>{{ taskInfo?.repairTeamName || '' }}</text>
									</view>
									<view class="record-item" v-show="taskInfo?.repairTeamUserName">
										<text>维修人</text>
										<text>{{ taskInfo?.repairTeamUserName || '' }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view v-show="tagCurrent === 1 && props.isRead == 0" class="detail card">
						<view class="flex flex-col justify-between flex-1 h-full">
							<view class="record-content">
								<view class="flex title justify-between" style="margin: 6px 0 !important">
									<text>备件更换</text>
								</view>
							</view>
							<view class="record-item">
								<view v-for="(item, index) in taskInfo.parts" :key="index">
									<view class="flex flex-col justify-between flex-1 h-full record-content-body">
										<view class="record-content">
											<view class="record-item">
												<text>{{ item.spareName }}</text>
												<text>{{ item.spareCode }}</text>
											</view>
											<view class="record-item" style="align-items: center">
												<view class="">
													<u-number-box :min="0" buttonSize="26" v-model="item.sparePartNumber"></u-number-box>
												</view>
												<u-icon name="trash" color="red" size="20" style="margin-right: -2px" @click="handleDelete(index)"></u-icon>
											</view>
										</view>
									</view>
									<u-divider style="margin: 0"></u-divider>
								</view>
								<u-button
									class="addBtn1"
									type="primary"
									text="新增"
									@click="jumpUrl('/pages/eam/equ/selectParts/index?assetKind=3')"
									style="height: 28px; width: 70px; text-align: center; justify-content: center; margin-left: 0; margin-top: 8px"
								></u-button>
							</view>
						</view>
					</view>
				</u--form>
			</view>
			<view class="flex controls">
				<!-- 待确认状态下，可以进行确认和返修操作 -->
				<button v-if="taskInfo.repairStatus == '0'" type="primary" class="submit_btn flex-1" @click="openPrompt(taskInfo, 1)">应 答</button>
				<button
					v-if="taskInfo.repairStatus == '1'"
					type="primary"
					:disabled="postLoading"
					:loading="postLoading"
					class="submit_btn flex-1"
					@click="openPrompt(taskInfo, 2)"
				>
					开始维修
				</button>
				<button v-if="props.isRead == 0 && taskInfo.repairStatus == '2'" :disabled="finishLoading" class="submit_btn orange-btn orange-shadow flex-1" @click="submit(2)">
					维修完成
				</button>
				<button v-if="props.isRead == 0" :disabled="postLoading" :loading="postLoading" type="primary" class="submit_btn flex-1" @click="submit(filterStatus())">
					保 存
				</button>
			</view>
		</view>
		<!-- 开始时间选择picker弹窗 -->
		<u-datetime-picker v-model="taskInfo.repairStartTimeCode" :show="showTime" mode="datetime" @cancel="showTime = false" @confirm="timeSelect"></u-datetime-picker>
		<!-- 结束时间选择picker弹窗 -->
		<u-datetime-picker v-model="taskInfo.repairEndTimeCode" :show="showTimeEnd" mode="datetime" @cancel="showTimeEnd = false" @confirm="timeSelectEnd"></u-datetime-picker>
		<!-- 故障模式 picker -->
		<u-picker :show="showModePicker" :columns="faultModeList" keyName="faultMode" immediateChange @cancel="showModePicker = false" @confirm="changeFaultMode"></u-picker>
		<!-- 班组选择 picker -->
		<u-picker
			:show="showCrewPicker"
			:columns="crewList"
			keyName="teamName"
			immediateChange
			@cancel="showCrewPicker = false"
			@confirm="changeCrew"
			class="crew-picker"
		></u-picker>
		<!-- 人员选择 picker -->
		<u-picker
			:show="showMemberPicker"
			:columns="memberList"
			keyName="memberName"
			immediateChange
			@cancel="showMemberPicker = false"
			@confirm="changeMember"
			class="member-picker"
		></u-picker>
		<u-modal :show="showImport" ref="uModal" :content="promptText" confirmText="确认" showCancelButton @cancel="cancelImport" @confirm="confirmImport" class="control-picker">
			<view class="slot-content">
				<text v-show="promptStatus !== 8 && promptStatus !== 9">{{ promptText }}</text>
				<view v-if="promptStatus === 8 || promptStatus === 9" class="" style="width: 550rpx">
					<view @click="hideKeyboard" class="flex input-box u-m-b-20">
						<u--input v-model="transferInfo.repairTeamName" placeholder="请选择维修班组" readonly class="input-self"></u--input>
					</view>
					<view @click="crewhideKeyboard" class="flex input-box">
						<u--input v-model="transferInfo.repairTeamUserName" placeholder="请选择维修人" readonly class="input-self"></u--input>
					</view>
				</view>
			</view>
		</u-modal>
		<u-action-sheet :actions="editList" cancelText="取 消" :show="showEdit" @close="showEdit = false" @select="selectEdit"></u-action-sheet>
		<!-- 树形选择器 -->
		<ba-tree-picker
			ref="positionPicker"
			:multiple="false"
			@select-change="positionChange"
			title="故障部位"
			:selectedData="showPositionValue"
			:localdata="faultPositionList"
			valueKey="id"
			textKey="organizationName"
			childrenKey="nodes"
		/>
	</view>
</template>

<script lang="ts" setup>
import { nextTick, ref, toRefs, watch, reactive, computed, toRaw } from 'vue';
import { onShow, onPullDownRefresh, onLaunch } from '@dcloudio/uni-app';
import UploadImage from '@/components/upload-image-ssr.vue';
import DeviceInfoTemplate from '@/pages/eam/mold/repairOrderCreate/components/deviceInfo.vue';
import RepairOrderInfo from '@/pages/eam/mold/repairOrderCreate/components/repairOrderInfo.vue';
import RepairHandleInfo from '@/pages/eam/mold/repairOrderCreate/components/repairHandleInfo.vue';
import { http } from '@/utils/http';
import { getSecondTime, getTimes, validateNumber, validateNumberCanNull } from '@/utils/common';
import { useUserStore } from '@/stores/useUserStore';
import { getCrewMemberListApi, getCrewListApi } from '@/api/jt-api';
import { useEamStore } from '@/stores/useEamStore';
import { useDictionaryStore } from '@/stores/useDictionaryStore';
import BaTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue';
import { CommonValue } from '@/types/type';
const props = defineProps({
	id: {
		type: String,
		default: ''
	},
	isRead: {
		type: String,
		default: '' // 1是查看
	},
	assetId: {
		// 设备Id
		type: String,
		default: ''
	},
	assetKind: {
		type: String,
		default: '1'
	},
	// 报修来源 按照字典表来 EamFaultSource
	repairSource: {
		type: String,
		default: '1'
	}
});

// 获取安全距离高度
const { safeAreaInsets } = uni.getSystemInfoSync();

// 顶部导航右侧操作
const showEdit = ref(false);
const editList = ref([
	{ value: 0, name: '转交' },
	// { value: 1, name: '指派' },
	{ value: 2, name: '委外' }
]);
function selectEdit(e: CommonValue) {
	if (e.value === 0) {
		// 转交
		openPrompt(taskInfo, 8);
	} else if (e.value === 1) {
		// 指派
		openPrompt(taskInfo, 9);
	} else if (e.value === 2) {
		// 委外
		uni.showToast({
			title: '敬请期待',
			icon: 'error'
		});
	}
	showEdit.value = true;
}

// tag切换功能
const tagCurrent = ref(0);
function selectTagHandle(index) {
	tagCurrent.value = index;
}

function filterStatus() {
	if (taskInfo.repairStatus != '0' && taskInfo.repairStatus != '1' && taskInfo.repairStatus != '2') {
		return 3;
	} else {
		return 1;
	}
}

// 显示选择器
const positionPicker = ref();
function showPositionPicker() {
	positionPicker.value._show();
}
//监听选择（ids为数组）
const showPositionValue = ref([]);
function positionChange(ids, names) {
	console.log('ids', ids);
	taskInfo.faultPositionId = ids[0] ?? '';
	taskInfo.faultPosition = names ?? '';
	showPositionValue.value = ids[0] ? [ids[0]] : [];
}

// 清空数据
function clearInfo(arr) {
	arr?.map((item) => {
		taskInfo[item] = '';
		if (item === 'faultPosition') {
			if (positionPicker.value?._reTreeList) {
				positionPicker.value._reTreeList();
			}
			// showPositionValue.value = []
		}
	});
}

// 获取设备故障位置列表
const faultPositionList = ref();
async function getPositionList() {
	const { data } = await http({
		method: 'POST',
		url: `/system/sysOrganization/getUsableTree`,
		data: {}
	});
	faultPositionList.value = data;
}

// 获取设备模式位置列表
let faultModeList = ref<any>([]);
async function getModeList() {
	const { data } = await http({
		method: 'POST',
		url: `/eam/eamfaultmode/getAvailableList`,
		data: { assetKind: props.assetKind }
	});
	faultModeList.value[0] = data;
}

// 开始时间选择
const showTime = ref(false);
function timeSelect(e) {
	taskInfo.repairStartTimeCode = e.value;
	taskInfo.repairStartTime = getTimes(e.value);
	showTime.value = false;
}
function openTimeSelect() {
	if (!taskInfo.repairStartTimeCode) {
		taskInfo.repairStartTimeCode = Number(new Date());
	}
	showTime.value = true;
	uni.hideKeyboard();
}

// 结束时间选择
const showTimeEnd = ref(false);
function timeSelectEnd(e) {
	taskInfo.repairEndTimeCode = e.value;
	taskInfo.repairEndTime = getTimes(e.value);
	showTimeEnd.value = false;
}
function openTimeSelectEnd() {
	if (!taskInfo.repairEndTimeCode) {
		taskInfo.repairEndTimeCode = Number(new Date());
	}
	showTimeEnd.value = true;
	uni.hideKeyboard();
}

// 获取当前页面实例
const pages = getCurrentPages();
// 获取当前页面的实例
const currentPage: any = pages[pages.length - 1];
// 获取页面路径
const pagePath = currentPage.$page.fullPath;

// 校验时间
function validateEndTime(rule: any, value: any, callback: any) {
	if ((taskInfo.repairStartTime && value < taskInfo.repairStartTime) || value == taskInfo.repairStartTime) {
		callback(new Error('结束时间不能小于或等于开始时间'));
	} else {
		callback();
	}
}
// 校验
function validateStartTime(rule: any, value: any, callback: any) {
	if ((taskInfo.repairEndTime && value > taskInfo.repairEndTime) || value == taskInfo.repairEndTime) {
		callback(new Error('开始时间不能大于或等于结束时间'));
	} else {
		callback();
	}
}

const realRules = {
	faultModeId: [{ required: true, message: '请选择故障模式', trigger: 'change' }],
	repairStartTime: [
		{ required: true, message: '请选择维修开始时间', trigger: 'blur' },
		{ validator: validateStartTime, trigger: 'change' }
	],
	repairEndTime: [
		{ required: true, message: '请选择维修结束时间', trigger: 'blur' },
		{ validator: validateEndTime, trigger: 'change' }
	],
	faultPhenomenon: [
		// { required: true, message: "请输入故障现象", trigger: "change" },
		{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
	],
	faultReason: [
		// { required: true, message: "请输入故障原因", trigger: "change" },
		{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
	],
	faultHandleMeasure: [
		// { required: true, message: "请输入故障处理措施", trigger: "change" },
		{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
	],
	repairUseTime: [
		// { required: true, message: "请输入维修用时", trigger: "blur" },
		{
			validator: validateNumberCanNull,
			trigger: 'blur'
		}
	],
	sonsparePartNumber: [
		{
			validator: validateNumber,
			trigger: 'blur'
		}
	]
};

const elderRules = {
	faultModeId: [],
	repairStartTime: [],
	repairEndTime: [],
	repairUseTime: [
		{
			validator: validateNumberCanNull,
			trigger: 'blur'
		}
	],
	faultPhenomenon: [{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
	faultReason: [{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
	faultHandleMeasure: [{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
	repairTime: [{ min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }],
	sonsparePartNumber: [
		{
			validator: validateNumber,
			trigger: 'blur'
		}
	]
};

// 表单规则定义
const rules = reactive({
	assetName: [{ required: true, message: '请选择设备', trigger: 'blur' }],
	// faultStatus: [{ required: true, message: '请选择故障状态', trigger: 'change' }],
	// repairLevel: [{ required: true, message: '请选择故障等级', trigger: 'change' }],
	faultModeId: [],
	repairStartTime: [],
	repairEndTime: [],
	faultPhenomenon: [{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
	faultReason: [{ min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }],
	faultHandleMeasure: [{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
	repairTime: [],
	repairUseTime: [
		{
			validator: validateNumberCanNull,
			trigger: 'blur'
		}
	],
	repairSituation: [
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	repairUserName: [{ min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }],
	repairTeamId: [{ message: '请选择维修班组', trigger: 'change' }],
	repairTeamUser: [{ message: '请选择维修人', trigger: 'change' }],
	sonsparePartNumber: [
		{
			validator: validateNumber,
			trigger: 'blur'
		}
	]
});

//班组
let crewList = ref<any>([]);
//人员
let memberList = ref<any>([]);

// 转交/指派功能数据定义
const transferInfo = reactive({
	repairTeamId: '',
	repairTeamCode: '',
	repairTeamName: '',
	repairTeamUser: '',
	repairTeamUserEmpNo: '',
	repairTeamUserName: ''
});

// 确认班组信息
const changeFaultMode = async (e) => {
	if (e?.value?.length) {
		taskInfo.faultModeId = e.value[0].id;
		taskInfo.faultMode = e.value[0].faultMode;
	} else {
		taskInfo.faultMode = '';
		taskInfo.faultModeId = '';
	}
	showModePicker.value = false;
};

// 确认班组信息
const changeCrew = async (e) => {
	if (e?.value?.length) {
		transferInfo.repairTeamCode = e.value[0].teamCode;
		transferInfo.repairTeamName = e.value[0].teamName;
		transferInfo.repairTeamId = e.value[0].id;
		getMembers(transferInfo.repairTeamId);
		clearRepairTeamUser();
	} else {
		clearRepairTeam();
		clearRepairTeamUser();
		memberList.value[0] = [];
	}
	showCrewPicker.value = false;
};
// 确认班组人员变化
const changeMember = (e: any) => {
	if (e?.value?.length) {
		transferInfo.repairTeamUserEmpNo = e.value[0].memberEmpNo;
		transferInfo.repairTeamUserName = e.value[0].memberName;
		transferInfo.repairTeamUser = e.value[0].id;
		// transferInfo.repairTeamUserText = e.value[0].repairTeamUserText;
	} else {
		transferInfo.repairTeamUserEmpNo = '';
		transferInfo.repairTeamUserName = '';
		transferInfo.repairTeamUser = '';
		// transferInfo.repairTeamUserText = '';
	}
	showMemberPicker.value = false;
};

// 清空联动维修人员信息
function clearRepairTeamUser() {
	transferInfo.repairTeamUserEmpNo = '';
	transferInfo.repairTeamUserName = '';
	transferInfo.repairTeamUser = '';
}

// 清空联动维修班组信息
function clearRepairTeam() {
	transferInfo.repairTeamCode = '';
	transferInfo.repairTeamName = '';
	transferInfo.repairTeamId = '';
}

// 获取班组列表
async function getCrews() {
	let list: any = (await getCrewListApi({ teamType: '1' })) || [];
	list.forEach((item) => {
		item.repairTeamText = `${item.teamCode}-${item.teamName}`;
	});
	crewList.value[0] = list;
}

// 获取人员列表
async function getMembers(id) {
	let list: any = (await getCrewMemberListApi({ id: id })) || [];
	list.forEach((item) => {
		item.repairTeamUserText = `${item.memberEmpNo}-${item.memberName}`;
	});
	memberList.value[0] = list;
}

getCrews();
/**
 * 选择故障模式
 */
const showModePicker = ref(false);

/**
 * 选择工作中心
 */
const showCrewPicker = ref(false);
/**
 * 选择班组
 */
const showMemberPicker = ref(false);

/**
 * 组织键盘弹出
 */
function modeHideKeyboard() {
	showModePicker.value = true;
	uni.hideKeyboard();
}
/**
 * 组织键盘弹出
 */
function hideKeyboard() {
	showCrewPicker.value = true;
	uni.hideKeyboard();
}
/**
 * 组织键盘弹出
 */
function crewhideKeyboard() {
	showMemberPicker.value = true;
	uni.hideKeyboard();
}

// 选择设备信息
const deviceList = computed(() => JSON.parse(useEamStore().deviceList));

// 网页跳转
function jump(item, id = '') {
	uni.navigateTo({
		url: id ? `/pages${item}?id=${id}` : `/pages${item}`,
		fail: () => {
			uni.showToast({
				title: '敬请期待',
				icon: 'error'
			});
		}
	});
}

// 跳转至备件页面
function jumpUrl(url) {
	uni.navigateTo({
		url: url,
		fail: () => {
			uni.showToast({
				title: '敬请期待',
				icon: 'error'
			});
		}
	});
}

// 是否折叠
const isCollapse = ref(true);

// 初始化页面，获取检查详情
let taskInfo = reactive<any>({
	id: '',
	// 设备信息
	assetId: '',
	assetName: '',
	assetCode: '',
	assetTypeName: '',
	assetModelNo: '',
	assetBrandName: '',
	usingDepartmentName: '',
	usingPersonName: '',
	locationName: '',
	// 故障信息
	images: [],
	executeFiles: [],
	faultStatus: '',
	repairLevel: '',
	remarks: '',
	memo: '',

	// 维修信息
	repairTeamId: '',
	repairTeamCode: '',
	repairTeamName: '',
	repairTeamText: '',

	repairTeamUser: '',
	repairTeamUserText: '',
	repairTeamUserName: '',
	repairTeamUserEmpNo: '',
	repairUseTime: '', // 维修用时

	// 以下为原生数据
	version: '',
	// assetTypeId: "",
	repairTime: '',
	repairUser: useUserStore().userInfo.userId,
	repairUserName: useUserStore().userInfo.userName,
	repairCode: '',
	// faultStatus: "",
	// repairLevel: "",
	// repairTeamId: "",
	// repairTeamUser: "",
	answerTime: '',
	repairStartTime: '',
	repairEndTime: '',
	repairStartTimeCode: '',
	repairEndTimeCode: '',
	faultMode: '',
	faultModeId: '',
	faultPhenomenon: '',
	faultPhenomenonId: '',
	faultReason: '',
	faultReasonId: '',
	faultPosition: '',
	faultPositionId: '',
	faultHandleMeasure: '',
	faultHandleMeasureId: '',
	parts: [],
	repairSituation: '',
	repairStatus: '',
	outSourcing: '',
	createTime: '',
	createdUserId: '',
	createdUserName: '',
	lastUpdateTime: '',
	lastUpdatedUserId: '',
	lastUpdatedUserName: '',
	enabled: '',
	deleted: '',
	assetKind: props.assetKind || '1',
	repairSource: props.repairSource || '1'
});
const loading = ref(false);

// 摄像头参数设置
const capture = ref(["camera",'album']);
const accept = ref('image');

// 获取现场图片
function getSceneExecuteFiles(list) {
	taskInfo.executeFiles = list;
}
function getImageFiles(list) {
	taskInfo.images = list;
}

// 校验提交
const uForm = ref();
const finishLoading = ref(false);
const postLoading = ref(false);
function submit(type: number) {
	// 确认提交时增加校验
	if (type === 2 || type === 3) {
		Object.assign(rules, { ...realRules });
	}
	const text = type == 3 ? '保存' : type == 1 ? '保存' : '维修';
	uForm.value
		.validate()
		.then(async () => {
			postLoading.value = true;
			if (type === 2) {
				finishLoading.value = true;
			}
			const result: any = await http({
				method: 'POST',
				url: `/eam/mouldrepairorder/save`,
				data: taskInfo
			}).finally(() => {
				postLoading.value = false;
				finishLoading.value = false;
			});

			if (type === 2) {
				openPrompt(taskInfo, 3);
			} else {
				uni.showToast({
					title: `${text}成功`
				});
				uni.navigateTo({
					url: `/pages/eam/mold/repairHandle/index`
				});
			}
			// 校验恢复
			Object.assign(rules, { ...elderRules });
		})
		.catch((e) => {
			console.log('catch', e);
		});
}

async function initPage() {
	try {
		loading.value = true;
		const result: any = await http({
			method: 'GET',
			url: `/eam/mouldrepairorder/get/${props.id}`,
			data: {
				assetKind: props.assetKind
			}
		}).finally(() => {
			uni.stopPullDownRefresh();
		});
		taskInfo = Object.assign(taskInfo, {
			...result.data,
			images: result.data.images || [],
			executeFiles: result.data.executeFiles || [],
			parts: result.data.parts || [],
			repairStartTimeCode: result.data.repairStartTime ? Number(new Date(result.data.repairStartTime)) : '',
			repairEndTimeCode: result.data.repairEndTime ? Number(new Date(result.data.repairEndTime)) : ''
		});

		if (taskInfo.repairTeamUserEmpNo) {
			getMembers(taskInfo.repairTeamId);
			taskInfo.repairTeamUserText = taskInfo.repairTeamUserEmpNo + '-' + taskInfo.repairTeamUserName;
		}
		if (taskInfo.repairTeamCode) {
			taskInfo.repairTeamText = taskInfo.repairTeamCode + '-' + taskInfo.repairTeamName;
			getMembers(taskInfo.repairTeamId);
		}
		loading.value = false;

		nextTick(() => {
			selectTagHandle(1);
		});
	} catch (e) {
		console.log(e);
	}
}

// 页面刷新
function refresh() {
	props.id && initPage();
}

// 下拉加载
onPullDownRefresh(() => {
	uni.showToast({
		title: 'onPullDownRefresh'
	});
	refresh();
});

// 页面显示回调
refresh();

// 过滤设备信息
function filterDeviceInfo(item) {
	taskInfo.parts.push({
		spareType: item.spareType,
		spareCode: item.spareCode,
		spareName: item.spareNmae,
		spareUnit: item.spareUnit,
		sparePartNumber: '',
		sparePartId: item.id
	});
}
/** 删除行 */
const handleDelete = (index: any) => {
	taskInfo.parts.splice(index, 1);
};
// 监控设备选择id
watch(
	() => deviceList,
	async (newVal) => {
		if (newVal.value[0]?.id) {
			filterDeviceInfo(newVal.value[0]);
		}
		setTimeout(() => {
			useEamStore().setDeviceList();
		}, 1000);
	},
	{
		deep: true,
		immediate: true
	}
);

//首次进入，新建状态，清空设备报修缓存
onShow(() => {
	// if (!props.id) {
	// 	useEamStore().setDeviceList();
	// }
	getPositionList();
	getModeList();
});

// 选择作业
const promptText = ref('');
const promptStatus = ref(null);
const promptReason = ref('');
function getStatusText(item, status) {
	promptReason.value = '';
	if (status === 1) {
		promptText.value = `请确认，是否应答编号为${item.repairCode}的报修单?`;
	} else if (status === 2) {
		promptText.value = `请确认，编号为${item.repairCode}的报修单是否开始维修?`;
	} else if (status === 3) {
		promptText.value = `请确认，编号为${item.repairCode}的报修单是否维修完成?`;
	}
}

const selectInfo = ref({});
const showImport = ref(false);
function openPrompt(row, status) {
	promptStatus.value = status;
	getStatusText(row, status);
	showImport.value = true;
	selectInfo.value = row;
}

// 取消选择
function cancelImport() {
	showImport.value = false;
	selectInfo.value = {};
	Object.assign(transferInfo, {
		repairTeamId: '',
		repairTeamCode: '',
		repairTeamName: '',
		repairTeamUser: '',
		repairTeamUserEmpNo: '',
		repairTeamUserName: ''
	});
}

function changeStatus() {
	return new Promise(async (resolve, reject) => {
		const res = await http({
			method: 'POST',
			url: '/eam/mouldrepairorder/updateStatus',
			data: {
				id: selectInfo.value.id,
				repairStatus: promptStatus.value
				// memo: promptStatus.value === 4 ? promptReason.value : ''
			}
		}).catch((e) => {
			// showImport.value = false;
		});
		resolve(res);
	});
}

// 转交
function transferHandle() {
	return new Promise(async (resolve, reject) => {
		const res = await http({
			method: 'POST',
			url: '/eam/mouldrepairorder/transmit',
			data: {
				id: taskInfo.id,
				...toRaw(transferInfo)
			}
		}).catch((e) => {});
		resolve(res);
	});
}

// 指派
function transferAssign() {
	return new Promise(async (resolve, reject) => {
		const res = await http({
			method: 'POST',
			url: '/eam/mouldrepairorder/assign',
			data: {
				id: taskInfo.id,
				...toRaw(transferInfo)
			}
		}).catch((e) => {});
		resolve(res);
	});
}

// 追加加工单
async function confirmImport() {
	if ((promptStatus.value === 8 || promptStatus.value === 9) && !transferInfo.repairTeamId) {
		uni.showToast({
			title: '请选择维修班组'
		});
		return;
	}
	if ((promptStatus.value === 8 || promptStatus.value === 9) && !transferInfo.repairTeamUserEmpNo) {
		uni.showToast({
			title: '请选择维修人'
		});
		return;
	}
	let code = null;
	if (promptStatus.value === 8) {
		const codeObj: any = await transferHandle();
		code = codeObj.code;
	} else if (promptStatus.value === 9) {
		const codeObj: any = await transferAssign();
		code = codeObj.code;
	} else {
		const codeObj: any = await changeStatus();
		code = codeObj.code;
	}
	if (code === 200) {
		cancelImport();
		uni.showToast({
			title: '操作成功'
		});
		let path = '';
		if (pagePath.includes('isRead=1')) {
			path = pagePath.replace('isRead=1', 'isRead=0');
		} else {
			path = pagePath;
		}
		if (promptStatus.value == 2) {
			uni.redirectTo({
				url: path
			});
		} else if (promptStatus.value == 1) {
			uni.redirectTo({
				url: pagePath
			});
		} else {
			// 页面回退
			uni.navigateTo({
				url: `/pages/eam/mold/repairHandle/index`
			});
		}

		// searchList()
	} else {
		uni.showToast({
			title: '操作失败'
		});
	}
	showImport.value = false;
}
</script>

<style lang="scss" scoped>
.handle-ok {
	min-width: 75px;
	color: #19be6b;
}
.card {
	background-color: #fff;
	margin: 10px 10px;
	border-radius: 8px;
	padding: 12px 12px;
	transition: all 300ms ease;
	box-shadow: 0 2px 6px rgba(3, 121, 255, 0.05);
}

.overhidden {
	overflow: hidden;
}

uni-page-body {
	height: 100%;
	background-color: #fbfbff;
}

.u-divider {
	margin: 10px 0;
}

.baseForm {
	background-color: #fbfbff;
	display: block;
	margin-top: 40px;
	padding-bottom: 50px;
}

.title {
	font-size: 16px;
	margin: 6px 0 14px;
	font-weight: bold;
	.u-icon {
		margin-right: 3px;
	}
}

.submit_btn {
	margin: 60rpx 20rpx;
	border-radius: 60rpx;
	height: 45px;
	font-size: 16px;
	line-height: 45px;
	box-shadow: 0 1px 10px rgba(3, 121, 255, 0.3);
}
.grey_btn {
	background-color: #fff !important;
	border: 1px solid #999;
	box-shadow: 0 1px 10px rgba(22, 37, 78, 0.08);
	color: #4f4f4f;
}

.searchScan {
	display: flex;
	height: 37px;
	padding: 12px 12px 0px;
	:deep(.u-input) {
		border: none;
		background-color: #fff !important;
		box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
	}
	.addBtn1 {
		width: 60px;
		height: 36px;
		margin-left: -3px !important;
		:deep(.u-button__text) {
			font-size: 14px !important;
		}
	}
}
:deep(.u-form-item__body) {
	padding: 4px 0 12px;
}
:deep(.u-number-box__input) {
	width: 60px !important;
}
:deep(.u-form-item) {
	.u-form-item__body__left__content__label {
		color: #a8b2bb;
		font-size: 14px;
		margin-bottom: 1px;
	}
	.u-form-item__body__left__content__required {
		font-size: 16px;
	}
	// 单选不可编辑样式
	.u-radio {
		.u-radio__icon-wrap--disabled {
			background-color: rgb(255, 255, 255) !important;
		}
		.u-radio__icon-wrap--disabled--checked {
			background-color: rgb(41, 121, 255) !important;
			border-color: rgb(41, 121, 255) !important;
			.u-icon__icon {
				color: #fff !important;
			}
		}
		.u-radio__text {
			color: #16254e !important;
			font-size: 14px !important;
		}
	}

	.u-textarea--disabled {
		background-color: #fff !important;
	}
	.uni-textarea-textarea {
		color: #16254e !important;
	}

	.input-box {
		width: 100%;
		border: 0.5px solid #dadbde !important;
		border-radius: 4px;
		.u-input {
			pointer-events: none;
			height: 34px;
			padding-left: 10px !important;
		}
		image {
			padding: 7px 6px;
			width: 20px;
			height: 20px;
		}
	}

	.input-box1 {
		width: 100%;
		border: 0.5px solid #dadbde !important;
		border-radius: 4px;
		.u-input {
			height: 34px;
			padding-left: 10px !important;
		}
		image {
			padding: 7px 6px;
			width: 20px;
			height: 20px;
		}
	}
}

.mt-10- {
	margin-top: -30px;
}

.controls {
	padding: 0 5px;
	position: fixed;
	bottom: 5px;
	left: 0;
	width: calc(100% - 10px);
	z-index: 99;
	.submit_btn {
		margin: 0px 5px;
		border-radius: 10px;
	}
}

// :deep(.repaire_tag_div) {
// 	width: 200px;
// 	margin: 0 auto;
// 	padding-top: 10px;
// 	display: flex;
// 	.u-subsection__bar--first {
// 	    border-top-left-radius: 20px;
// 	    border-bottom-left-radius: 20px;
// 	}
// 	.u-subsection__bar--last {
// 	    border-top-right-radius: 20px;
// 	    border-bottom-right-radius: 20px;
// 	}
// 	.u-subsection__item--first {
// 		border-top-left-radius: 20px;
// 		border-bottom-left-radius: 20px;
// 	}
// 	.u-subsection__item--last {
// 		border-top-right-radius: 20px;
// 		border-bottom-right-radius: 20px;
// 		background-color: #fff;
// 	}
// }
.repaire_tag_div {
	display: flex;
	justify-content: center;
	width: 100%;
	.repaire_tag {
		width: 200px;
		padding-top: 10px;
		display: flex;
		.tag_item {
			flex: 1;
			border: 1px solid #0379ff;
			background-color: #fff;
			text-align: center;
			font-size: 14px;
			color: #0379ff;
			padding: 5px 12px;
		}
		.tag_item:nth-child(1) {
			border-top-left-radius: 20px;
			border-bottom-left-radius: 20px;
		}
		.tag_item:nth-last-child(1) {
			border-top-right-radius: 20px;
			border-bottom-right-radius: 20px;
		}
		.active_tag {
			background-color: #0379ff !important;
			color: #fff !important;
			font-weight: bold !important;
		}
	}
}
:deep(.control-picker) {
	.u-transition {
		z-index: 1000 !important;
	}
}
:deep(.crew-picker) {
	.u-transition {
		z-index: 1001 !important;
	}
}
:deep(.member-picker) {
	.u-transition {
		z-index: 1001 !important;
	}
}
</style>
